import Taro, { Component, Config } from '@tarojs/taro'
import { Image, ScrollView, Text, View } from '@tarojs/components'
import { OSS } from '@/config/config'
import { headImg } from "@/utils/utils"
import Calc from "@/utils/calc"
import classNames from 'classnames'
import { toGoodsPage } from '@/utils/page_router'
import moment from '@/assets/js/moment.min'
import { getCurrencyTime } from '@/api/commonApi'
import { getProduct, getHours } from '@/api/strategiesApi'
import {FyImg, Loading, LoadMore} from '@/components/index'
import './index.scss'
import { getAppConfig } from '@/utils/storage'
import GoodsList from './goodsList/index'

const statusName = {
  '-1': '已结束',
  0: '未开始',
  1: '立即购买'
}
const fun = function () {}
export default class Index extends Component {
  state: any
  rolling: boolean
  config: Config = {
    backgroundTextStyle: "dark",
    navigationBarTitleText: '限时秒杀',
    navigationBarTextStyle: 'white',
    navigationBarBackgroundColor: '#E93423'
  }

  constructor() {
    super(...arguments)
    this.state = {
      loading: true,
      showBg: false,
      nodeTop: 0,
      showLoad: true,
      tabKey: 0,
      tabList: [],
      goodsList: []
    }
    this.rolling = true
  }

  componentWillMount() {
    this.getPage().then()
  }

  componentDidMount() {
    this.getNode()
  }

  //  页面滚动触发事件的处理函数
  onPageScroll({ scrollTop }) {
    if (this.rolling) {
      return false
    }

    const { showBg, nodeTop } = this.state
    const bool = scrollTop >= nodeTop
    if (showBg !== bool) {
      this.setState({
        showBg: bool
      })
    }
  }

  getNode () {
    const query = Taro.createSelectorQuery()
    query.select('#tab-scroll').boundingClientRect(rect => {
      this.setState({
        nodeTop: rect.top
      }, () => {
        this.rolling = false
      })
    }).exec()
  }


  //  获取今日活动
  async getPage() {
    const time = await getCurrencyTime()
    const hour = moment.unix(time.data).hour()
    getHours().then(({ data }) => {
      const tabList = data.map(time => ({
        time,
        status: time < hour ? '已结束' : time > hour ? '即将开始' : '抢购中'
      }))
      const ind = data.findIndex(i => i === hour)
      this.setState({
        tabKey: ind >= 0 ? ind : 0,
        tabList,
        timeList: data
      }, () => {
        this.getGoods()
      })
    })
  }

  //  获取活动商品
  getGoods() {
    const { tabKey, timeList } = this.state
    getProduct(timeList[tabKey]).then(({ data }) => {
      this.setState({
        loading: false,
        showLoad: false,
        goodsList: data
      })
    })
  }

  //  切换 tab
  onSwitchTab(key) {
    this.setState({
      tabKey: key,
      showLoad: true,
      goodsList: []
    }, () => {
      this.getGoods()
    })
  }

  render() {
    const { loading, tabKey, tabList, showBg, showLoad, goodsList } = this.state
    return (<View className='page'>
      {loading && <Loading/>}
      <View className='page-scroll'>
        <View className='seckill_bg f-g-2'>
          {getAppConfig('commonName')}秒杀
          {/*<FyImg src={`${OSS}/system/image/seckill_bg.png`} className='seckill_img'/>*/}
        </View>
        <ScrollView scrollX id='tab-scroll' className={classNames('tab-scroll', {
          'tab-scroll__bg thin-border__b': showBg
        })}>
          <View className='tab-list'>
            <View className='tab-item j-c-c'>
              <FyImg src={`${OSS}/system/image/seckill_time_title.png`} className='tab-img'/>
            </View>
            {
              tabList.map((tab, key) => {
                return (
                  <View key={tab} className={classNames('tab-item', {
                    'tab-active': key === tabKey
                  })} onClick={key === tabKey?this.onSwitchTab.bind(this, key):fun()}>
                    <View className='tab-time bnn-number'>{tab.time}:00</View>
                    <View className='tab-text f-g-5'>{tab.status}</View>
                  </View>
                )
              })
            }
          </View>
        </ScrollView>
        <GoodsList list={goodsList} />
        {/*<View className='goods-list'>*/}
          {/*{*/}
          {/*  goodsList.map(goods => {*/}
          {/*    const number = Math.round((Calc.Div(goods.salesNumber || 0, Calc.Add(goods.stockNumber || 0, goods.realSalesNumber || 0))) * 100)*/}
          {/*    const percent = goods.stockNumber > 0 && number <= 100 ? number : 100*/}
          {/*    return (*/}
          {/*      <View key={goods.id} className='goods-item f-g-4' onClick={() => toGoodsPage(goods)}>*/}
          {/*        <Image src={headImg(goods.images)} className='goods-img'/>*/}
          {/*        <View className='goods-info d-f f-d-c'>*/}
          {/*          <View className='goods-name t-o-e-2'>{goods.productName}</View>*/}
          {/*          <View className='goods-price d-f a-i-b bnn-number'>*/}
          {/*            <View className='sale-price'>*/}
          {/*              <Text className='sale-price__unit'>￥</Text>*/}
          {/*              {goods.salePrice}*/}
          {/*            </View>*/}
          {/*            <View className='origin-price'>￥{goods.originPrice}</View>*/}
          {/*          </View>*/}
          {/*          <View className='goods-desc'>*/}
          {/*            {goods.limitNumber ? `限量 ${goods.limitNumber} 件`: ''}*/}
          {/*          </View>*/}
          {/*          <View className='progress'>*/}
          {/*            <View className='progress-bg' style={{ width: `${percent}%` }}/>*/}
          {/*            <View className='progress-text'>{Math.floor(percent)}%</View>*/}
          {/*          </View>*/}
          {/*          <View className='buy-btn f-g-5' hoverClass='hover-class--btn'>{statusName[goods.status]}</View>*/}
          {/*        </View>*/}
          {/*      </View>*/}
          {/*    )*/}
          {/*  })*/}
          {/*}*/}
        {/*</View>*/}
        {showLoad && <LoadMore status='loading'/>}
      </View>
    </View>)
  }
}
